
package main

import (
	"encoding/hex"
	"fmt"
	"github.com/ethereum/go-ethereum/accounts/keystore"
	"github.com/ethereum/go-ethereum/crypto"
	"io/ioutil"
	"log"
	"os"
)

func main() {
	if len(os.Args) != 3 {
		fmt.Println("export-swarm-key <sourceDir> <password>")
		return
	}

	keystorePath := os.Args[1]
	passwordPath := os.Args[2]

	// privKey, address, err := KeystoreToPrivateKey("/home/xingzjx/project/go/exportSwarmKey/S120.240.50.172bee1/keystore1.json", "SmuJbPATma2zCGES9pFPQl_8H1SjhwDZ")

	privKey, address, err := KeystoreToPrivateKey(keystorePath, passwordPath)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("privKey:%s\naddress:%s\n", privKey, address)

	// 3e6666708d8e529a53aef232592d015362e659ca52dfba931b8f8a2092a21715
}

func KeystoreToPrivateKey(privateKeyFile string, passwordPath string) (string, string, error) {
	keyjson, err := ioutil.ReadFile(privateKeyFile)
	if err != nil {
		fmt.Println("read keyjson file failed：", err)
	}
	password, err := ioutil.ReadFile(passwordPath)
	if err != nil {
		fmt.Println("read password file failed：", err)
	}
	unlockedKey, err := keystore.DecryptKey(keyjson, string(password))
	if err != nil {
		return "", "", err
	}
	privKey := hex.EncodeToString(unlockedKey.PrivateKey.D.Bytes())
	addr := crypto.PubkeyToAddress(unlockedKey.PrivateKey.PublicKey)
	return privKey, addr.String(), nil
}
